<?php declare(strict_types=1);

namespace App\Exception\Handler;

use App\Exception\HttpExecption;
use ReflectionException;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
use Throwable;

/**
 * Class HttpExceptionHandler
 *
 * @ExceptionHandler(\Throwable::class)
 */
class HttpExceptionHandler extends AbstractHttpErrorHandler
{
    private $errorCode=1;
    private $data = [];
    private $httpCode = 500;
    /**
     * @param Throwable $e
     * @param Response   $response
     *
     * @return Response
     * @throws ReflectionException
     * @throws ContainerException
     */
    public function handle(Throwable $e, Response $response): Response
    {
        if($e instanceof HttpExecption){
            $this->errorCode = $e->getErrorCode();
            $this->data = $e->getData();
            $this->httpCode = $e->getCode();
        }
        $data = return_msg($this->errorCode,$e->getMessage(),$this->data);
        return $response->withStatus($this->httpCode)->withData($data);
    }
}
